<template>
  <div>
  <el-page-header @back="clickIndexLeft" content="详情页面"> </el-page-header>
  <el-divider/>
  <el-row justify="center">
    <!--返回-->
    <el-button type="primary" @click="startScan">检票</el-button>
    <el-button type="warning" @click="closeScan">停止检票</el-button>
    <el-divider/>
    <!-- 扫码区域 -->
    <div class="scan" v-if="!openVideo"></div>
    <video ref="video" width="500" height="360" id="video" v-if="openVideo"></video>
    <el-divider/>
    <!-- 提示语 -->
    <div v-show="tipShow" class="scan-tip"> {{tipMsg}} </div>
  </el-row>
  </div>
</template>

<script>
import { BrowserMultiFormatReader } from '@zxing/library';
import {updateStatus} from "@/api/ticket";
import {wsURlMulti} from "@/setting";

export default {
  name: 'scanCodePage',
  data() {
    return {
      openVideo:false,
      loadingShow: false,
      codeReader: null,
      scanText: '',
      vin: null,
      tipMsg: '正在尝试识别....',
      tipShow: false
    }
  },
  mounted() {

    this.localSocket()
  },
  unmounted(){
    this.codeReader&&this.codeReader.reset();
    this.codeReader=null
     this.ws.close()
  },
  methods: {
    closeScan(){
      this.codeReader&&this.codeReader.reset();
      this.codeReader=null
      this.tipShow=false
      this.openVideo=false
    },
    startScan(){
      this.openVideo=true
      this.codeReader = new BrowserMultiFormatReader();
      this.openScan();
    },
    async openScan() {
      this.codeReader.getVideoInputDevices().then((videoInputDevices) => {
        this.tipShow = true;
        this.tipMsg = '正在调用摄像头...';
        // 默认获取第一个摄像头设备id
        let firstDeviceId = videoInputDevices[0].deviceId;
        // 获取第一个摄像头设备的名称
        const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);
        if (videoInputDevices.length > 1) {
          // 判断是否后置摄像头
          if (videoInputDeviceslablestr.indexOf('back') > -1) {
            firstDeviceId = videoInputDevices[0].deviceId;
          } else {
            firstDeviceId = videoInputDevices[1].deviceId;
          }
        }
        this.decodeFromInputVideoFunc(firstDeviceId);
      }).catch(err => {
        this.tipShow = false;
        console.error(err);
      });
    },
    decodeFromInputVideoFunc(firstDeviceId) {
      this.codeReader.reset(); // 重置
      this.scanText = '';
      this.codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId, 'video', (result, err) => {
        this.tipMsg = '正在尝试识别...';
        this.scanText = '';
        if (result) {
          if (result.getText().substring(2,8)!=='scenic'){
            this.$message({
              type:'error',
              message:'二维码无效'
            })
            this.tipShow = false;
            this.codeReader&&this.codeReader.reset()
            this.codeReader=null
            return
          }
          this.scanText = JSON.parse(result.getText());
          if (this.scanText.hasOwnProperty('scenic')&&this.scanText.scenic==='yun') {
           this.updateStatus(this.scanText)
          }
        }
        if (err && !(err)) {
          this.tipMsg = '识别失败';
          setTimeout(() => {
            this.tipShow = false;
          }, 2000)
          console.error(err);
        }
      });
    },
    updateStatus(ticket){
      const a=Date.parse(ticket.enterTime)
      const startTime=new Date(a)
      startTime.setHours(6)
      startTime.setMinutes(30)
      startTime.setSeconds(0)
      const endTime=new Date(a)
      endTime.setHours(19)
      endTime.setMinutes(30)
      endTime.setSeconds(0)
      const nowTime=Date.now()
      if (nowTime<startTime || nowTime>endTime ||ticket.status!=='UN_USE'){
        this.tipShow = false;
        this.codeReader&&this.codeReader.reset()
        this.codeReader=null
        this.ws.send(JSON.stringify({toName:ticket.userid,message:'CANT|SCAN'}))
        this.$message({
          type:'error',
          message:'未到检票时间或门票已过期'
        })
      }else {
        updateStatus(ticket.id,'USING').then(()=>{
          this.tipShow = false;
          this.codeReader&&this.codeReader.reset()
          this.codeReader=null
          this.ws.send(JSON.stringify({toName:ticket.userid,message:'ticketUSING'}))
        })
      }

    },
    clickIndexLeft(){  // 返回上一页
      this.codeReader&&this.codeReader.reset()
      this.codeReader=null
        this.$router.back()
    },
    localSocket() {
      let that = this;
      const userId = this.$store.state.user.userId;
      if ("WebSocket" in window) {
        //建立websocket连接
        // that.ws = new WebSocket(`ws://localhost:8002/ticket/${userId}`);
        that.ws = new WebSocket(`${wsURlMulti}${userId}`);
        // that.$websocket.setWsT(that.ws)
        that.ws.onopen=function (){
          // console.log("已连接")
        }

        //连接关闭
        that.ws.onclose = function() {
          // 关闭 websocket
          // console.log("连接已关闭");
        }
        //连接错误
        that.ws.onerror=function(e){
          console.log("连接错误！")
        }
      } else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!");
      }
    },
  }
}
</script>

<style lang="less" scoped>
.scan{
  width: 500px;
  height: 360px;
  border: 1px solid crimson ;
}
</style>
